#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <stdbool.h>
#include "iniparser.h"
#include "dictionary.h"

#define INI_FILE "boq.ini"

static int boq_ini_save(char *section,char *key, char *value)
{
	FILE  *fp = NULL  ;
	dictionary *ini= NULL;
	char item[128]={0};

    if (access(INI_FILE, F_OK))
    {
        fp = fopen(INI_FILE, "w");
       if(fp) 
       {
         fputs("[INI]\n", fp);
         fclose(fp);
       }
    }

	ini = iniparser_load(INI_FILE);
	if( ini == NULL)
	{
		printf("iniparser  failure\n");
		return -1;
	}

	sprintf(item,"%s:%s",section,key);
	
	iniparser_set(ini, item, value);

	fp = fopen(INI_FILE, "w");
	if( fp == NULL ) {
		printf("stone:fopen error!\n");
		exit(-1);
	}

	iniparser_dump_ini(ini, fp);
	fclose(fp);
	iniparser_freedict(ini);
}

static int boq_ini_str_get(char *section,char *key, char *dst, char *def)
{
	FILE  *fp = NULL  ;
	dictionary *ini= NULL;
	char item[128]={0};

    if (access(INI_FILE, F_OK))
    {
        fp = fopen(INI_FILE, "w");
       if(fp) 
       {
         fputs("[INI]\n", fp);
         fclose(fp);
       }
    }

	ini = iniparser_load(INI_FILE);
	if( ini == NULL)
	{
		printf("iniparser  failure\n");
		return -1;
	}

	sprintf(item,"%s:%s",section,key);

    strcpy(dst,iniparser_getstring(ini, item, def));

	iniparser_freedict(ini);
}

void bytes_to_hex(char *bytes, int len, char *hex)
{
    for(size_t i = 0; i < len; i++) {
        sprintf(hex + i*2, "%02X", bytes[i]);
    }
}


int hex_to_bytes(char *hex, char *bytes, int len)
{
    for(size_t i = 0; i < len; i++) {
        if(sscanf(hex + i*2, "%2hhx", &bytes[i]) != 1) return -1;
    }
    return 0;
}

void ini_sn_set(char *value)
{
    boq_ini_save("INI", "sn", value);
}

void ini_sn_get(char *dst)
{
    boq_ini_str_get("INI", "sn", dst, "00C31976084");
}

void ini_key_set(char *value)
{
    boq_ini_save("INI", "key", value);
}

void ini_key_get(char *dst)
{
    boq_ini_str_get("INI", "key", dst, "NULL");
}

void ini_userID_set(char *value)
{
    boq_ini_save("INI", "userID", value);
}

void ini_userID_get(char *dst)
{
    boq_ini_str_get("INI", "userID", dst, "");
}



